package com.itfreer.security;

import android.app.Activity;
import android.app.ProgressDialog;

import com.itfreer.data.config.ConfigService;
import com.itfreer.utils.config.ConfigManager;
import com.itfreer.utils.volley.callback.DataCallback;
import com.itfreer.utils.common.ToastUtils;

import java.util.Map;

/**
 * 安全服务，定义系统登录授权
 */
public class SecurityService {

    /**
     * 单一实例
     */
    public static final SecurityService instance = new SecurityService();

    private UserInfoEntity user;
    private ProgressDialog loginDialog;
    private UserChangeListener userChangeListener;
    private UserLoginListener userLoginListener;

    private SecurityService() {
    }

    /**
     * 获取登录的用户
     * @return
     */
    public UserInfoEntity getUser(){
        return user;
    }

    /**
     * 设置监听
     * @param listener
     */
    public void setUserChangeListener(UserChangeListener listener){
        userChangeListener = listener;
    }

    /**
     * 用户登录监听
     * @param listener
     */
    public void setUserLoginListener(UserLoginListener listener){
        userLoginListener = listener;
    }

    /**
     * 初始化用户登录信息
     */
    public void init(final Activity main){
        SecurityDataService.instance.getCurrentUser(new DataCallback<UserInfoEntity>(){
            @Override
            public void result(UserInfoEntity userInfoEntity) {
                user = userInfoEntity;
                if(userChangeListener!=null){
                    userChangeListener.change(user);
                }
            }

            @Override
            public void error(int status, String info) {
                user = null;
                if(userChangeListener!=null){
                    userChangeListener.change(user);
                }
                if(ConfigManager.getConfig("tgt")!=null && !ConfigManager.getConfig("tgt").toString().trim().equals("")){
                    innerLogin(false, main);
                }
            }
        });
    }

    /**
     * 系统登录
     * @param username
     * @param password
     */
    public void login(String username, String password, final Activity main){
        if (username == null || username.trim().equals("")){
            ToastUtils.showShort(main, "用户名不能为空！");
            if(userLoginListener!=null){
                userLoginListener.onFail();
            }
            return;
        }

        if (password == null || password.trim().equals("")){
            ToastUtils.showShort(main, "密码不能为空！");
            if(userLoginListener!=null){
                userLoginListener.onFail();
            }
            return;
        }

        loginDialog = ProgressDialog.show(main, "登录中..", "验证用户密码..", true, true);
        SecurityDataService.instance.createTickets(username,password,new DataCallback<Map>(){
            @Override
            public void result(Map map) {
                if(map.containsKey("ok")){
                    String tgt = map.get("ok").toString();
                    ConfigManager.setConfig("tgt", tgt);
                    ConfigService.instance.update();
                    innerLogin(true, main);
                } else {
                    loginDialog.dismiss();
                    loginDialog = null;
                    ToastUtils.showShort(main, "用户密码错误！");
                    if(userLoginListener!=null){
                        userLoginListener.onFail();
                    }
                }
            }

            @Override
            public void error(int status, String info) {
                loginDialog.dismiss();
                loginDialog = null;
                if(status==-1){
                    ToastUtils.showShort(main, info);
                }else{
                    ToastUtils.showShort(main, "用户密码错误！");
                    if(userLoginListener!=null){
                        userLoginListener.onFail();
                    }
                }
            }
        });
    }

    /**
     * 内部登录
     */
    private void innerLogin(final boolean isUI, final Activity main){
        String ssoService = ConfigManager.getConfig("ssoService").toString();
        String tgt = ConfigManager.getConfig("tgt").toString();
        if (tgt == null || tgt.trim().equals("") || ssoService == null || ssoService.trim().equals("")){
            if (loginDialog!=null){
                loginDialog.dismiss();
                loginDialog = null;
            }
            if(isUI){
                ToastUtils.showShort(main, "票据获取失败！");
            }
            if(userLoginListener!=null){
                userLoginListener.onFail();
            }
            return;
        }

        if (loginDialog!=null){
            loginDialog.setMessage("验证登录票据中...");
        }
        SecurityDataService.instance.createServiceTickets(tgt, ssoService, new DataCallback<Map>(){
            @Override
            public void result(Map map) {
                String st = map.get("ok").toString();
                SecurityDataService.instance.mklogin(st, new DataCallback<Map>(){
                    @Override
                    public void result(Map map) {
                        String jwt = map.get("jwt").toString();
                        ConfigManager.setConfig("jwt", jwt);
                        ConfigService.instance.update();
                        if (loginDialog!=null){
                            loginDialog.setMessage("获取用户信息...");
                        }
                        SecurityDataService.instance.getCurrentUser(new DataCallback<UserInfoEntity>(){
                            @Override
                            public void result(UserInfoEntity userInfoEntity) {
                                user = userInfoEntity;
                                if(userChangeListener!=null){
                                    userChangeListener.change(user);
                                }

                                if (loginDialog!=null){
                                    loginDialog.dismiss();
                                    loginDialog = null;
                                }
                                if(userLoginListener!=null){
                                    userLoginListener.onSuccess(user);
                                }
                            }
                            @Override
                            public void error(int status, String info) {
                                if (loginDialog!=null){
                                    loginDialog.dismiss();
                                    loginDialog = null;
                                }
                                if(userLoginListener!=null){
                                    userLoginListener.onFail();
                                }
                            }
                        });
                    }

                    @Override
                    public void error(int status, String info) {
                        if (loginDialog!=null){
                            loginDialog.dismiss();
                            loginDialog = null;
                        }
                        if(isUI){
                            if(status==-1){
                                ToastUtils.showShort(main, info);
                            }else{
                                ToastUtils.showShort(main, "登录验证失败！");
                            }
                            if(userLoginListener!=null){
                                userLoginListener.onFail();
                            }
                        }
                    }
                });
            }

            @Override
            public void error(int status, String info) {
                if (loginDialog!=null){
                    loginDialog.dismiss();
                    loginDialog = null;
                }
                if(isUI){
                    if(status==-1){
                        ToastUtils.showShort(main, info);
                    }else{
                        ToastUtils.showShort(main, "登录验证失败！");
                    }
                }
                if(userLoginListener!=null){
                    userLoginListener.onFail();
                }
            }
        });
    }

    /**
     * 退出系统
     */
    public void logout(){
        String jwt = ConfigManager.getConfig("jwt").toString();
        ConfigManager.setConfig("tgt", "");
        ConfigManager.setConfig("jwt", "");
        ConfigService.instance.update();
        user = null;
        if(userChangeListener!=null){
            userChangeListener.change(user);
        }
        SecurityDataService.instance.loginOut(jwt, null);
    }

    /**
     * 用户注册
     * @param ac
     * @param pw
     * @param rpw
     */
    public void userRegister(String ac, String pw, String rpw, final Activity main){
        if (ac == null || ac.trim().equals("")){
            ToastUtils.showShort(main, "用户名不能为空！");
            return;
        }

        if (pw == null || pw.trim().equals("")
                || rpw == null || rpw.trim().equals("")
                || !pw.equals(rpw)){
            ToastUtils.showShort(main, "密码为空，或不一至！");
            return;
        }

        loginDialog = ProgressDialog.show(main, "注册中..", "请稍后..", true, true);
        SecurityDataService.instance.userRegister(ac, pw, rpw, new DataCallback<Map>() {
            @Override
            public void result(Map map) {
                loginDialog.dismiss();
                loginDialog = null;
                ToastUtils.showShort(main, "注册成功！");
            }

            @Override
            public void error(int status, String info) {
                loginDialog.dismiss();
                loginDialog = null;
                if(status==-1){
                    ToastUtils.showShort(main, info);
                }else{
                    ToastUtils.showShort(main, "注册失败，帐号已存在！");
                }
            }
        });
    }

    /**
     * 设置密码
     * @param pw
     * @param rpw
     */
    public void setPassword(String op, String pw, String rpw, final Activity main) {
        if (pw == null || pw.trim().equals("")
                || rpw == null || rpw.trim().equals("")
                || !pw.equals(rpw)){
            ToastUtils.showLong(main, "密码为空，或不一至！");
            return;
        }

        loginDialog = ProgressDialog.show(main, "密码设置中..", "请稍后..", true, true);
        SecurityDataService.instance.setPassword(op, pw, new DataCallback<Boolean>() {
            @Override
            public void result(Boolean result) {
                if(result){
                    ToastUtils.showLong(main, "设置成功！");
                }else{
                    ToastUtils.showLong(main, "设置失败，请确认输入密码正确！");
                }
                loginDialog.dismiss();
                loginDialog = null;
            }

            @Override
            public void error(int status, String info) {
                loginDialog.dismiss();
                loginDialog = null;

                if(status==-1){
                    ToastUtils.showLong(main, info);
                }else{
                    ToastUtils.showLong(main, "设置失败，请重新登录系统后重试！");
                }
            }
        });
    }

}